package cc.idoone.spring_boot_hello.mybatis.h2;

/**
 * 配置Mapper的扫描包路径
 *
 * @auther hemj
 * @since 2017/10/20
 */

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * 配置Mapper的扫描包路径
 */
@Configuration
@EnableTransactionManagement
// @MapperScan(
// 		basePackages = "cc.idoone.spring_boot_hello.mybatis.h2.dao",
// 		sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisScanConfiguration {

	@Bean(name = "myh2DataSource")
	@ConfigurationProperties(prefix = "spring.datasource.myh2")
	public DataSource h2DataSource() {
		return DataSourceBuilder.create().build();
	}

	/**
	 * 根据数据源创建 SqlSessionFactory
	 */
	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("myh2DataSource") DataSource h2DataSource) throws Exception {
		SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
		fb.setDataSource(h2DataSource); //指定数据源(这个必须有，否则报错)

		// 下边仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
		fb.setTypeAliasesPackage("cc.idoone.spring_boot_hello.mybatis.**.entity"); //指定基包
		// 添加XML目录
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		fb.setMapperLocations(resolver.getResources("classpath*:mybatis/**/*.xml"));

		return fb.getObject();
	}

	@Bean(name = "sqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	/**
	 * 配置事务管理器
	 */
	@Bean(name = "h2MyBatisTransactionManager")
	public DataSourceTransactionManager transactionManager(@Qualifier("myh2DataSource") DataSource h2DataSource) throws Exception {
		return new DataSourceTransactionManager(h2DataSource);
	}

}
